package com.chuck.blogpro.controller;

import com.chuck.blogpro.pojo.Result;
import com.chuck.blogpro.pojo.User;
import com.chuck.blogpro.service.UserService;
import com.chuck.blogpro.utils.JWTUtils;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 登录管理
 */
@RestController
public class LoginController {

    @Autowired
    private UserService userService;

    /**
     * 登录:
     * 登录成功后，保存数据到 Jwt
     * 最后返回 Jwt 数据
     */
    @PostMapping("/login")
    public Result login(User user) {
        System.out.println(user);
        User user1 = userService.getUser(user);
        if (user1 != null) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", user.getId());
            map.put("username", user.getUsername());
            String jwt = JWTUtils.createToken(map);
            return Result.success(jwt);
        }
        return Result.error("用户名或密码错误");
    }

//    MARK：- cookie、session 测试方法
//    @GetMapping("/setCookie")
//    public Result setCookie(HttpServletRequest request) {
//        Cookie cookie = new Cookie("username", "chuck");
//        cookie.setMaxAge(60 * 60 * 24);
//        cookie.setPath("/");
//        request.getSession().setAttribute("username", "chuck");
//        return Result.success("cookie");
//    }
//
//    @GetMapping("/getCookie")
//    public Result getCookie(HttpServletRequest request) {
//        Cookie[] cookies = request.getCookies();
//        for (Cookie cookie : cookies) {
//            System.out.println(cookie.getName() + ":" + cookie.getValue());
//        }
//        return Result.success("cookie");
//    }
//
//    @GetMapping("/getSession")
//    public Result getSession(HttpServletRequest request) {
//        Object username = request.getSession().getAttribute("username");
//        return Result.success(username);
//    }
//
//    @GetMapping("/setSession")
//    public Result setSession(HttpServletRequest request) {
//        request.getSession().setAttribute("username", "chuck");
//        return Result.success("session");
//    }
}

